package com.lingx.web.api.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.lingx.bean.ContextBean;
import com.lingx.bean.TokenBean;
import com.lingx.bean.UserBean;
import com.lingx.model.IContext;
import com.lingx.model.impl.DefaultEntity;
import com.lingx.service.DefaultValueService;
import com.lingx.service.InterpretService;
import com.lingx.service.ModelService;
import com.lingx.utils.TokenUtils;
import com.lingx.web.api.IApi;
@Component
public class Api8013 extends AbstractAuthApi implements IApi{
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private DefaultValueService defaultValueService;
	@Resource
	private ModelService modelService;
	@Override
	public int getApiCode() {
		return 8013;
	}
	@Override
	public String getApiName() {
		return "获取表单配置";
	}
	@Override
	public Map<String, Object> api(Map<String, Object> param) {
		Map<String,Object> ret=IApi.getRetMap(1, "操作成功");
		if(this.checkIsNull(param, "ecode",ret))return ret; 
		if(this.checkIsNull(param, "mcode",ret))return ret; 
		String ecode=IApi.getParamString(param, "ecode", "");
		String mcode=IApi.getParamString(param, "mcode", "");
		TokenBean token=TokenUtils.getTokenData(param.get("lingxtoken").toString());
		UserBean userBean =new UserBean();
		userBean.setId(token.getUserId());
		userBean.setOrgId(token.getOrgId());
		IContext context = new ContextBean(userBean,null,null);
		List<Map<String,Object>> list=this.jdbcTemplate.queryForList("select content from tlingx_form where ecode=? and mcode=? and status='1' limit 1",ecode,mcode);
		if(list.size()==0) {
			ret.put("code", -1);
			ret.put("message", "未设置相应的表单");
			return ret;
		}
		Map<String,Object> map=null;
		if(list.get(0).get("content")!=null) {
			String json=list.get(0).get("content").toString();
			if(json.trim().startsWith("{")) {
				map=(Map<String,Object>)JSON.parse(json);
				list=(List<Map<String,Object>>)map.get("list");
				for(Map<String,Object> m:list) {
					if(m.get("value")!=null&&!"".equals(m.get("value").toString())) {
						m.put("value", this.defaultValueService.transform(m.get("value").toString(),param, context));
					}
					switch(m.get("type").toString()) {
					case "radio":
					case "combobox":
						m.put("optionitem", this.getOptionitems(m.get("optioncode")));
						break;
					case "checkbox":
						m.put("optionitem", this.getOptionitems(m.get("optioncode")));
						m.put("value",this.getArray(m.get("value")) );
						break;
					case "griddialog":
					case "griddialog2":
					case "treedialog":
					case "treedialog2":
						if(m.get("ecode")!=null&&!"".equals(m.get("ecode").toString())&&m.get("value")!=null&&!"".equals(m.get("value").toString())) {
						m.put("value",this.getObjectValues(m.get("ecode").toString(),m.get("value").toString()) );
						}
						break;
					}
				}
			}
		}
		if(map==null)map=new HashMap<>();
		
		ret.put("data", map);
		return ret;
	}
	private String[] getArray(Object value) {
		if(value==null)return new String[] {};
		if("".equals(value.toString().trim()))return new String[] {};
		return value.toString().split(",");
	}
	private List<Map<String,Object>> getOptionitems(Object code){
		if(code==null)code="SF10";
		List<Map<String,Object>> items=this.jdbcTemplate.queryForList("select name text,value from tlingx_optionitem where enabled=1 and option_id in (select id from tlingx_option where code=?) order by orderindex asc ",code);
		return items;
		 
	}
	
	public List<Map<String,Object>>  getObjectValues(String ecode,String value) {
		List<Map<String,Object>> listMap=null;
		String sql = "select %s,%s from %s where %s='%s' %s";
		String insql = "select %s,%s from %s where %s in(%s) %s";
		List<String> listField=null,paramField;
		DefaultEntity subEntity = modelService.getEntity(ecode);
		if (subEntity == null)
			return listMap;
		String ename=subEntity.getName(),params="";
		String tableName = subEntity.getTableName();
		String vField = modelService.getValueField(subEntity);
		listField = modelService.getTextField(subEntity);
		paramField= modelService.getParamField(subEntity);
		
		
		try {
			List<String> allList=new ArrayList<>();
			allList.addAll(listField);
			allList.addAll(paramField);
			if (value.indexOf(",") != -1){
				listMap =this.jdbcTemplate.queryForList(
						String.format(insql,this.modelService.getStringByList(allList),vField, tableName, vField,InterpretService.toArrayString(value), params));
				
			}else{
				listMap = this.jdbcTemplate.queryForList(
						String.format(sql,this.modelService.getStringByList(allList),vField, tableName, vField,value, params));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		{
			String text="";
			if(listMap==null)listMap=new ArrayList<Map<String,Object>>();
			if (listMap.size()==0){//listMap == null
				
				Map<String,Object> map=new HashMap<String,Object>();
				map.put("text", value);
				map.put("value",value);
				map.put("id", value);
				map.put("etype", ecode);
				map.put("ecode", ecode);
				map.put("ename", ename);
				map.put("islink", false);
				
				listMap.add(map);
			}else{
				for(Map<String,Object> map:listMap){
					StringBuilder sb = new StringBuilder();
					for (String s : listField) {
						sb.append(map.get(s.toUpperCase())).append("-");
					}
					sb.deleteCharAt(sb.length() - 1);
					text=sb.toString();
					
					map.put("text", sb.toString());
					//map.put("value", m.get(field.getCode()));
					map.put("value", map.get(vField));
					map.put("etype", ecode);
					map.put("ecode", ecode);
					map.put("ename", ename);

					map.put("islink", false);
					for(String str:paramField) {
						map.put(str, map.get(str));
					}
					
				}
			}
			
			return listMap;
			
		}
	}

	public boolean isLog() {
		return false;
	}
}
